//创建用户相关的仓库
import { defineStore } from 'pinia'
//引入本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, DEL_TOKEN } from '@/utils/token'
import type { UserState } from './types/type'
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index'
//引入常量路由
import { constantRoute, asyncRoute, randomRoute } from '@/router/routes'
//引入数据类型
import { loginFormData, loginResponseData, userInfoResponseData } from '@/api/user/type'
import router from '@/router'

//引入深拷贝方法
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
import type { RouteRecordRaw } from 'vue-router'

function filterAsyncRoute(asyncRoute: any, arr: any) {
  const tmp = asyncRoute
  return tmp.filter((item: any) => {
    if (arr.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, arr)
      }
      return true
    }
  })
}

const useUserStore = defineStore('User', {
  /**
   * The state of the user store, with strongly typed properties.
   */
  state(): UserState {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute as RouteRecordRaw[],
      username: '',
      avatar: '',
    }
  },
  //方法
  //引入真实接口后，有变化的代码后面都用 // 标记
  actions: {
    //别用箭头函数，因为这里需要用到this指针！
    async login(loginForm: loginFormData): Promise<string> {
      //
      //获取登录的状态
      const result: loginResponseData = await reqLogin(loginForm)
      if (result.code === 200) {
        SET_TOKEN(result.data) //result.data.token(原)
        this.token = result.data //result.data.token
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data)) //result.data.message
      }
    },
    async getUserInfo(): Promise<string> {
      const result: userInfoResponseData = await reqUserInfo()
      if (result.code === 200) {
        //根据用户信息筛选路由
        this.username = result.data.name //result.data.checkUser.name
        this.avatar = result.data.avatar //result.data.checkUser.avatar
        //获取动态路由信息
        //把深拷贝的数据进行过滤
        const async = filterAsyncRoute(asyncRoute, result.data.routes)
        //更新总路由信息
        this.menuRoutes = [...constantRoute, ...async, randomRoute]
        //注册追加的路由
        const arr = [...async, randomRoute]
        arr.forEach((route: any) => {
          router.addRoute(route)
        })

        return 'ok'
      } else {
        return Promise.reject(new Error(result.message)) //'获取用户信息失败'
      }
    },
    async logout(): Promise<string> {
      const result: any = await reqLogout()
      if (result.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        DEL_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
